'''
Created on Sep 6, 2011

@author: david
'''
from app.G6.actions import G6Action

class List(G6Action):
    """
    Default Action 
    spawns index.gen
    """
    def execute(self):
        import logging
        from app.G6.agents import BlogAgent
        import json
        rv = []
        
        req = self.request
        
        try:
            # validate session
            if not self.auth_check():
                return self.JSONOutput(json.dumps({"results":"401::Invalid Session"}))
            
            agent = BlogAgent()
            acct = req.session.getAttribute("acct")
            blogs = agent.fetchBlogs(acct)
            
            # set up current blog
            curr = None
            for blog in blogs:
                logging.debug("~~ %s" % blog)
                if blog.default == 'True':
                    curr = blog
                rv.append(blog.toJSON())
            if not curr:
                curr = blogs[0]
                
            req.session.setAttribute('currblog', blog)
            
        except Exception, ex:
            logging.exception("!! Blog List Exception")
            
            return self.JSONOutput(json.dumps({"results":"500::%s" % str(ex)}))    
        
        return self.JSONOutput(json.dumps({"results":"200::OK","blogs": rv }))
